#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
通过SAX方式解析xml文档。
@author:zhuyan
@file: xmlutil.py
@time: 2018/08/19
"""
from xml.dom.minidom import *
import os.path, os


class XmlUtil:

    def __init__(self):
        self.impementation = DOMImplementation()

    def create_doc(self):
        doc = self.impementation.createDocument("", "goods", doctype=None)
        doc.createTextNode("text")
        doc.createAttribute("attr")
        print(doc.toxml())

    def read_doc(self):
        doc = parse("dt.xml")   #解析指定文档，此处也可传入文件名
        doc2 = parseString("<a>test</a>")
        print(doc.toxml())  #　打印整个文档结构
        root = doc.documentElement
        print(root.childNodes[1].toxml())  # 查找指定的子元素
        print(root.lastChild.toxml())  #  找到最后一个元素

    def traversal_doc(self, node):
        if not node.childNodes:
            return
        first = node.firstChild
        next = first
        while next:
            print(next)
            self.traversal_doc(next)
            next = next.nextSibling

    def get_elem_by_tag(self, root):
        shirt = root.getElementsByTagName("sec2")
        print(shirt[0].toxml())   #根据标签名查找子元素

        print(root.toxml())


if __name__ == '__main__':
    util = XmlUtil()
    # util.create_doc()
    # util.read_doc()

    doc = parse("dt.xml")
    # util.traversal_doc(doc.documentElement)
    util.get_elem_by_tag(doc.documentElement)

